package com.dq;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName Response
 * @Description response返回
 * @Author DuX1aoQiang
 * @Date 2023/5/28 20:10
 * @Version 1.0
 */
public class Response extends AbstractHttpServletResponse {
    private int status = 200;
    private String message = "ok";
    private Map<String, String> headers = new HashMap<>();
    private Request request;
    private OutputStream outputStream;
    private byte SP = ' ';
    private byte CR = '\r'; //回车
    private byte LF = '\n'; //换行
    private ResponseServletOutputStream responseServletOutputStream = new ResponseServletOutputStream(); //一个操作只需要一个响应体

    public Response(Request request) {
        this.request = request;
        try {
            this.outputStream = request.getSocket().getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void setStatus(int i, String s) {
        status = i;
        message = s;
    }

    @Override
    public int getStatus() {
        return status;
    }

    @Override
    public void addHeader(String s, String s1) {
        headers.put(s, s1);
    }

    @Override
    public ResponseServletOutputStream getOutputStream() throws IOException {
        return responseServletOutputStream;
    }

    //todo 真正实现 发送resp得数据
    public void complete() {
        try {
            sendResponseLine();
            sendResponseHeader();
            sendResponseBody();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void sendResponseLine() throws IOException {
        outputStream.write(request.getProtocol().getBytes());  //协议
        outputStream.write(SP);
        outputStream.write(status);  //协议
        outputStream.write(SP);
        outputStream.write(message.getBytes());  //协议
        outputStream.write(CR);
        outputStream.write(LF);
    }

    //如果addHeader  则遍历header
    private void sendResponseHeader() throws IOException {
        if (!headers.containsKey("Content-Length")){
            addHeader("Content-Length",String.valueOf(getOutputStream().getPos()));
        }

        if (!headers.containsKey("Content-Type")){
            addHeader("Content-Type","text/plain;charset=utf-8");
        }

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            outputStream.write(key.getBytes());
            outputStream.write(":".getBytes());
            outputStream.write(value.getBytes());
            outputStream.write(CR);
            outputStream.write(LF);
        }
        outputStream.write(CR);
        outputStream.write(LF);
    }

    private void sendResponseBody() throws IOException {
        outputStream.write(getOutputStream().getBytes());
    }


}
